package com.example.springworkadmin;

import com.example.springworkadmin.service.MyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyUserService myUserService;
    @Override

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication().withUser("admin").password("{noop}123456").roles("ADMIN").authorities("ADMIN");
        auth.userDetailsService(myUserService);
    }

    @Override

    public void configure(WebSecurity web){

        web.ignoring().antMatchers("/css/**", "/img/**", "/**/*.png");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .headers().frameOptions().disable().and()
                // 配置安全过滤链只拦载检查 '/admin/**' 的请求，并配置需要的权限。
                .antMatcher("/admin/**")
                .authorizeRequests().antMatchers("/admin/userAccount/**").hasAuthority("SUPER")
                .anyRequest().hasAuthority("ADMIN").and()
                // 自定义登录界面
                .formLogin()
                .loginPage("/admin/login_backend").permitAll()
                // 设置默认身份认证成功后跳转的页面,即直接访问登录界面时，认证成功后跳转的页面。
                .defaultSuccessUrl("/admin").and()
                // 自定义退出登录请求Url、成功退出登录后的重定向Url
                .logout()
                .logoutUrl("/admin/logout").permitAll()
                .logoutSuccessUrl("/admin/login_backend?logout");

    }
}
